/**
 * Created by IntelliJ IDEA.
 * User: p.popov
 * Date: 27.03.13
 * Time: 15:34
 * To change this template use File | Settings | File Templates.
 */
package slicesPanels {

public class Slice9Panel extends CSprite {
    private var innerWidth:Number;
    private var innerHeight:Number;
    private var innerScaleX:Number = 1;
    private var innerScaleY:Number = 1;
    private var settings:Slice9PanelSettings;
    private var centerPart:Slice9PanelPart;
    private var topLeftPart:Slice9PanelPart;
    private var topPart:Slice9PanelPart;
    private var topRightPart:Slice9PanelPart;
    private var leftPart:Slice9PanelPart;
    private var rightPart:Slice9PanelPart;
    private var bottomLeftPart:Slice9PanelPart;
    private var bottomPart:Slice9PanelPart;
    private var bottomRightPart:Slice9PanelPart;
    private var partsLoadedCount:int = 0;
    private var atlasPath: String;

	private var isNormalScale:Boolean = false;
    public function Slice9Panel(settings:Slice9PanelSettings, atlasPath:String, normalScale:Boolean = false) {
        this.settings = settings;
        this.atlasPath = atlasPath;
	    this.isNormalScale = normalScale;
        init();
    }

    private function init():void {
        topLeftPart = createImage(Slice9PartType.LEFT_TOP, [settings.topLeft]);
        addChild(topLeftPart);

        topPart = createImage(Slice9PartType.TOP, [settings.top, settings.center]);
        addChild(topPart);

        topRightPart = createImage(Slice9PartType.RIGHT_TOP, [settings.topRight, settings.topLeft]);
        addChild(topRightPart);

        leftPart = createImage(Slice9PartType.LEFT, [settings.left, settings.top, settings.center]);
        addChild(leftPart);

        if(settings.center){
            centerPart = createImage(Slice9PartType.CENTER, [settings.center]);
            addChild(centerPart);
        }

        rightPart = createImage(Slice9PartType.RIGHT, [settings.left, settings.top, settings.center]);
        addChild(rightPart);

        bottomLeftPart = createImage(Slice9PartType.LEFt_BOTTOM, [settings.bottomLeft, settings.topLeft]);
        addChild(bottomLeftPart);

        bottomPart = createImage(Slice9PartType.BOTTOM, [settings.bottom, settings.top, settings.center]);
        addChild(bottomPart);

        bottomRightPart = createImage(Slice9PartType.RIGHT_BOTTOM, [settings.bottomRight, settings.bottomLeft, settings.topLeft]);
        addChild(bottomRightPart);
    }

    private function createImage(type:Slice9PartType, resIds:Array):Slice9PanelPart {
        var image:Slice9PanelPart = Slice9PanelPart.create(type, resIds, "");
        image.setLoadCallback(onLoadingComplete);
        return image;
    }

    private function onLoadingComplete():void {
        partsLoadedCount++;
        readjustSize();
    }

    private function readjustSize():void {
        if (resourcesLoaded() && sizeInitialized()) {
            initScale();
            stretchParts();
            arrange();
        }
    }

    override public function getSize():Size {
        return new Size(innerWidth * scaleX, innerHeight * scaleY);
    }

    private function resourcesLoaded():Boolean {
        if(centerPart){
            return partsLoadedCount == 9;
        } else {
            return partsLoadedCount == 8;
        }
    }

    private function sizeInitialized():Boolean {
        return innerWidth > 0 && innerHeight > 0;
    }

    private function arrange():void {
        topLeftPart.setPosition(0, 0);
        topPart.setPosition(topLeftPart.x + topLeftPart.width, 0);
        topRightPart.setPosition(innerWidth - topRightPart.pivotX, 0);
        leftPart.setPosition(0, topLeftPart.height);
        if(centerPart){
            centerPart.setPosition(topPart.x, leftPart.y);
        }
        //rightPart.setPosition(centerPart.x + centerPart.width, leftPart.y);
        rightPart.setPosition(topRightPart.x, leftPart.y);
        bottomLeftPart.setPosition(0, leftPart.y + leftPart.height);
        bottomPart.setPosition(bottomLeftPart.x + bottomLeftPart.width, bottomLeftPart.y);
        bottomRightPart.setPosition(bottomPart.x + bottomPart.width, bottomLeftPart.y);

    }

    private function stretchParts():void {
        topPart.setSize(new Size(Math.max((innerWidth - (2 * topLeftPart.width)), 0), topLeftPart.height));
        leftPart.setSize(new Size(topLeftPart.width, Math.max((innerHeight - topLeftPart.height-bottomLeftPart.height), 0)));
        if(centerPart){
            centerPart.setSize(new Size(topPart.width, leftPart.height));
        }
        rightPart.setSize(new Size(topRightPart.width, leftPart.height));
        bottomPart.setSize(new Size(topPart.width, bottomLeftPart.height));
    }

    private function initScale():void {

        // сбросим
        topLeftPart.scaleX = topRightPart.scaleX = bottomLeftPart.scaleX = bottomRightPart.scaleX = 1;
        topLeftPart.scaleY = topRightPart.scaleY = bottomLeftPart.scaleY = bottomRightPart.scaleY = 1;

        innerScaleX = Math.min(innerWidth / ((topLeftPart.width + topRightPart.width)), 1);
        innerScaleY = Math.min(innerHeight / ((topLeftPart.height + bottomLeftPart.height)), 1);
        innerScaleX = innerScaleY = Math.min(innerScaleX, innerScaleY) * 1;
	    // свичка для перехода на нормальные ресайзнутые картинки, потом уберем когда все перерисуют
	    if(isNormalScale) {
	        innerScaleX = 1;
	        innerScaleY = 1;
        }

        // если уголки не влезают в указанные размеры, то уменьшим их
        if(topLeftPart.height + bottomLeftPart.height > innerHeight){
            innerScaleY = 0.99*innerHeight/(topLeftPart.height + topRightPart.height);
        }
        if(topLeftPart.width + topRightPart.width > innerWidth){
            innerScaleX = 0.99*innerWidth/(topLeftPart.width + topRightPart.width);
        }

        // пусть будет пропорционально
        if(isNormalScale) {
            innerScaleX = innerScaleY = Math.min(innerScaleX, innerScaleY);
        }

        topLeftPart.scaleX = topRightPart.scaleX = bottomLeftPart.scaleX = bottomRightPart.scaleX = innerScaleX;
        topLeftPart.scaleY = topRightPart.scaleY = bottomLeftPart.scaleY = bottomRightPart.scaleY = innerScaleY;
    }

    override public function setSize(size:Size):void {
        innerWidth = size.width;
        innerHeight = size.height;
        readjustSize();
    }

    override public function set width(width:Number):void {
        innerWidth = width;
        readjustSize();
    }

    override public function set height(height:Number):void {
        innerHeight = height;
        readjustSize();
    }

    override public function get width():Number {
        return innerWidth * scaleX;
    }

    override public function get height():Number {
        return innerHeight * scaleY;
    }

	override public function setChildrenColor(color:int):void {
		for (var i:int = 0; i < numChildren; i++){
			if(getChildAt(i) is Slice9PanelPart) {
				const sprite:Slice9PanelPart = Slice9PanelPart(getChildAt(i));
				sprite.setChildrenColor(color);
			}
		}
	}
}
}
